function showInfoWindow(position, queryResult) {
    var features = queryResult.features;
    if (features.length == 0) {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
    } else {
        var rows = [];
        var fields = [];
        var allFeatures = features;
        var firstFeatureProp = features[0].properties;
        for (var key in firstFeatureProp) {
            fields.push(key);
        }
        var content = "<table><tbody>";
        for (var k = 0; k < fields.length; k++) {
            var fieldName = fields[k];
            var fieldAlise = fieldName;
            if (fieldName == "OBJECTID") {
                continue;
            }
            if (fieldName == "SHAPE_Area") {
                continue;
            }
            if (fieldName == "SHAPE_Leng") {
                continue;
            }
            content += "<tr><th>";
            if (fields[k] == "MODEL_NAME")
                fieldAlise = "模型名称";
            if (fields[k] == "MinHeight")
                fieldAlise = "最低高度";
            if (fields[k] == "MaxHeight")
                fieldAlise = "最高高度";
            if (fields[k] == "x")
                fieldAlise = "经度";
            if (fields[k] == "y")
                fieldAlise = "纬度";
            if (fields[k] == "Height")
                fieldAlise = "房高";
            content += fieldAlise;
            content += ":</th><td>";
            if (fields[k].indexOf("Height") != -1) {
                content += firstFeatureProp[fields[k]].toFixed(2);
            } else {
                content += firstFeatureProp[fields[k]];
            }
            content += "</td></tr>";
        }
        content += "</tbody></table>";
        var obj = { position: position, content: content };
        infoWindow(obj);
    }
}

function changeFeaturesForMap3DTable(queryResult) {
    if (!queryResult || !queryResult.features || queryResult.features.length == 0) {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
    } else {
        var features = queryResult.features;
        var rows = [];
        var fields = [];
        var allFeatures = features;


        var firstFeatureProp = features[0].properties;
        for (var key in firstFeatureProp) {
            if (key && key.toLowerCase().indexOf("shape") == -1 && key.toLowerCase().indexOf("object") == -1) {
                fields.push(key);
            }
        }
        features = [];
        for (var i = 0; i < allFeatures.length; i++) {
            features.push(allFeatures[i].properties);
        }

        //将查询结果拼接成json格式数据
        for (var j = 0; j < features.length; j++) {
            var feature = features[j];
            var row = {};
            for (var k = 0; k < fields.length; k++) {
                var fieldName = fields[k];
                if (fieldName == "AREA") {
                    row[fieldName] = parseFloat(feature[fields[k]]).toFixed(2);
                    continue;
                }
                row[fieldName] = feature[fields[k]];
            }
            row["geom"] = JSON.stringify(allFeatures[j].geometry);
            rows.push(row);
        }

        var contentJson = {
            "total": features.length,
            "totalNotFiltered": features.length,
            "rows": rows
        };
        var titles = [];
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            if (field.toLowerCase() == "objectid" || field.toLowerCase().indexOf("shape") > -1) {
                continue;
            }
            titles.push(field);
        }
        titles.push("geom");
        createTable(titles, contentJson);
        addQueryFeatures(allFeatures);
    }
}

function createTable(titles, contentJson) {
    $("#queryTable").html("<div id='queryTable_tab0' lay-filter='queryTable_tab0'></div>");
    $("#queryResult").show();
    var colsArr = [];
    var a = [];
    for (var i = 0; i < titles.length; i++) {
        var obj = {
            field: titles[i],
            title: titles[i],
            width: 100,
            sort: true
        }
        if (titles[i] == "geom") {
            obj.hide = true;
        }
        a.push(obj);
    }
    colsArr.push(a);
    table.render({
        elem: '#queryTable_tab0',
        height: 312,
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print'],
        data: contentJson.rows,
        page: true, //开启分页
        cols: colsArr,
        text: {
            none: '暂无数据'
        }
    });
    table.on('row(queryTable_tab0)', function (obj) {
        if (obj.data.geom) {
            addSelectedFeature(JSON.parse(obj.data.geom));
        }
    });
    $(".layui-laypage select option").css("background", "#213457");
}

function changeFeaturesForTabTable(queryResults, copy) {
    removeAllEntities();
    if (queryResults.length > 0) {
        $("#queryTable").html("");
        $("#queryResult").show();

        var html = '<div class="layui-tab">';
        var tabTitle = '<ul class="layui-tab-title">';
        var tabContent = '<div class="layui-tab-content">';
        for (var i = 0; i < queryResults.length; i++) {
            tabContent += '<div class="layui-tab-item ' + (i == 0 ? "layui-show" : "") + '"><table lay-filter="queryTable_' + queryResults[i].id + '" id="queryTable_' + queryResults[i].id + '"></table></div>';
            tabTitle += '<li ' + (i == 0 ? 'class="layui-this"' : "") + '>' + queryResults[i].name + '</li>';
        }
        tabTitle += '</ul>';
        tabContent += '</div>';
        html += tabTitle + tabContent + '</div>';

        $("#queryTable").html(html);
        for (var y = 0; y < queryResults.length; y++) {
            var queryResult = queryResults[y].data;
            var features = queryResult.features;
            var rows = [];

            var fields = [];
            var allFeatures = features;
            var firstFeatureProp = features[0].properties;
            for (var key in firstFeatureProp) {
                if (key && key.toLowerCase().indexOf("shape") == -1 && key.toLowerCase().indexOf("object") == -1) {
                    fields.push(key);
                }
            }
            fields
            features = [];
            for (var i = 0; i < allFeatures.length; i++) {
                // 绘制结果 
                // var dataArr = allFeatures[i].geometry.coordinates[0][0];
                // var newdata = ToWGS84(dataArr, true);
                // addClapFeature(newdata);
                features.push(allFeatures[i].properties);
            }

            //将查询结果拼接成json格式数据
            for (var j = 0; j < features.length; j++) {
                var feature = features[j];
                var row = {};
                for (var k = 0; k < fields.length; k++) {
                    var fieldName = fields[k];
                    if (fieldName == "AREA") {
                        row[fieldName] = parseFloat(feature[fields[k]]).toFixed(2);
                        continue;
                    }
                    row[fieldName] = feature[fields[k]];
                }
                row["geom"] = JSON.stringify(allFeatures[j].geometry);
                rows.push(row);
            }

            var contentJson = {
                "total": features.length,
                "totalNotFiltered": features.length,
                "rows": rows
            };
            var titles = [];
            //根据查询结果构建列
            var columns = [];

            for (var i = 0; i < fields.length; i++) {
                var field = fields[i];
                if (field.toLowerCase() == "objectid") {
                    continue;
                }
                titles.push(field);
            }
            titles.push("geom");
            createTabTable(titles, contentJson, queryResults[y].id, copy);
            addQueryFeatures(allFeatures);
        }
    } else {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
    }
}

function createTabTable(titles, contentJson, id, copy) {
    var colsArr = [];
    var a = [];
    if (copy) {
        a.push({ field: 'copy', title: '操作', width: 65, templet: '#copyBoxTpl', unresize: true });
    }
    for (var i = 0; i < titles.length; i++) {
        var obj = {
            field: titles[i],
            title: titles[i],
            width: 100,
            sort: true
        }
        if (titles[i] == "geom") {
            obj.hide = true;
        }
        a.push(obj);
    }
    colsArr.push(a);
    table.render({
        elem: '#queryTable_' + id,
        height: 312,
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print'],
        data: contentJson.rows,
        page: true, //开启分页
        cols: colsArr,
        size: "sm",
        text: {
            none: '暂无数据'
        }
    });
    table.on('row(queryTable_' + id + ')', function (obj) {
        if (obj.data.geom) {
            addSelectedFeature(JSON.parse(obj.data.geom));
        }
    });
    layui.$('.copydemo').on('click', function (evt) {
        window.parent.parent.$(".json-textarea").show();
        window.parent.parent.$(".json-textarea").val(evt.target.value);
        evt.stopPropagation();
    });
    $(".layui-laypage select option").css("background", "#213457");
}

function addSelectedFeature(geom, zppmTo) {
    viewer.entities.removeById("selected_entity");
    var geomtype = geom.type.toLowerCase();
    var entity = null;
    var destination;
    if (geomtype.indexOf("polygon") > -1) {
        var points = [];
        if(!geom.coordinates[0][0]) {
            console.log("数据问题！");
            return;
        }
        for (var i = 0; i < geom.coordinates[0][0].length; i++) {
            points.push(geom.coordinates[0][0][i][0]);
            points.push(geom.coordinates[0][0][i][1]);
        }
        destination = Cesium.Cartesian3.fromDegreesArray(points);
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            polygon: {
                hierarchy: destination,
                //material: Cesium.Color.GREEN.withAlpha(0.7)
                material: Cesium.Color.RED.withAlpha(0.8)
            }
        });
        viewer.flyTo(entity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 100.0
            }
        });
    } else if (geomtype.indexOf("polyline") > -1) {
        var points = [];
        for (var i = 0; i < geom.coordinates[0][0].length; i++) {
            points.push(geom.coordinates[0][0][i][0]);
            points.push(geom.coordinates[0][0][i][1]);
        }
        destination = Cesium.Cartesian3.fromDegreesArray(points);
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            polyline: {
                positions: destination,
                material: Cesium.Color.RED,
                width: 5.0
            }
        });
        viewer.flyTo(entity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 0.0
            }
        });
    } else if (geomtype.indexOf("point") > -1) {
        destination = Cesium.Cartesian3.fromDegrees(geom.coordinates[0], geom.coordinates[1]);
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            position: destination,
            point: {
                color: Cesium.Color.GREEN.withAlpha(0.7),
                pixelSize: 10,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                outlineColor: Cesium.Color.YELLOW,
                outlineWidth: 2,
            }
        });
        viewer.flyTo(entity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 0.0
            }
        });
    }
}

function addQueryFeatures(features) {
    for (var m = 0; m < features.length; m++) {
        var geom = features[m].geometry;
        var geomtype = geom.type.toLowerCase();
        if (geomtype.indexOf("polygon") > -1) {
            var points = [];
            if(!geom.coordinates[0][0]) {
                console.log("数据问题！");
                continue;
            }
            for (var i = 0; i < geom.coordinates[0][0].length; i++) {
                points.push(geom.coordinates[0][0][i][0]);
                points.push(geom.coordinates[0][0][i][1]);
            }
            viewer.entities.add({
                polyline: {
                    positions: Cesium.Cartesian3.fromDegreesArray(points),
                    width: 2.0,
                    clampToGround: true,
                    material: Cesium.Color.fromCssColorString('#00ffff')
                }
                //polygon: {
                //    hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                //    material: Cesium.Color.RED.withAlpha(0.5)
                //}
            });
        } else if (geomtype.indexOf("polyline") > -1) {
            var points = [];
            for (var i = 0; i < geom.coordinates[0][0].length; i++) {
                points.push(geom.coordinates[0][0][i][0]);
                points.push(geom.coordinates[0][0][i][1]);
            }
            viewer.entities.add({
                polyline: {
                    positions: Cesium.Cartesian3.fromDegreesArray(points),
                    width: 4.0,
                    material: Cesium.Color.fromCssColorString('#00ffff')
                }
            });
        } else if (geomtype.indexOf("point") > -1) {
            viewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(geom.coordinates[0], geom.coordinates[1]),
                point: {
                    color: Cesium.Color.RED.withAlpha(0.5),
                    pixelSize: 10,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    outlineColor: Cesium.Color.YELLOW,
                    outlineWidth: 2,
                }
            });
        }
    }
}

function closeQueryToolbar() {
    removeAllEntities();
    pointHandler && pointHandler.clear();
    polylineHandler && polylineHandler.clear();
    polygonHandler && polygonHandler.clear();
};